import { Button, Form, Modal } from 'antd';
import type React from 'react';
import toast from 'react-hot-toast';
import EditTradeInfoForm from './EditTradeInfoForm';

interface AdminTradeModalProps {
  visible: boolean;
  onCancel: () => void;
  trade: any;
  onSuccess: () => void;
}

const AdminTradeModal: React.FC<AdminTradeModalProps> = ({
  visible,
  onCancel,
  trade,
  onSuccess,
}) => {
  const [form] = Form.useForm();

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload = {
        ...values,
        tradeDate: values.tradeDate.toISOString(),
      };

      const response = await fetch(
        `http://localhost:8000/trades/${trade.tradeID}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        },
      );

      if (response.ok) {
        toast.success('交易信息修改成功');
        onSuccess();
        onCancel();
      } else {
        const errorData = await response.json();
        toast.error(errorData.detail || '修改失败');
      }
    } catch (error) {
      toast.error('表单验证失败');
    }
  };

  const handleDelete = async () => {
    try {
      const response = await fetch(
        `http://localhost:8000/trades/${trade.tradeID}`,
        {
          method: 'DELETE',
        },
      );

      if (response.ok) {
        toast.success('交易删除成功');
        onSuccess();
        onCancel();
      } else {
        const data = await response.json();
        toast.error(data.detail || '删除失败');
      }
    } catch (error) {
      toast.error('网络错误');
    }
  };

  return (
    <Modal
      title={`交易详情 - ${trade.tradeID}`}
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="delete" type="primary" danger onClick={handleDelete}>
          删除交易
        </Button>,
        <Button key="submit" type="primary" onClick={handleOk}>
          提交修改
        </Button>,
      ]}
    >
      <EditTradeInfoForm trade={trade} form={form} />
    </Modal>
  );
};

export default AdminTradeModal;
